#include <stdarg.h>
#include <stdio.h>
#include <ctype.h>

// minprintf: minimal printf with variable argument list
void minprintf(char *fmt, ...)
{
	va_list ap;		// points to each unnamed arg in turn
	char *p, *sval;
	int ival;
	double dval;
	char pfmt[50];
	unsigned uval;

	va_start(ap, fmt);	// make ap point to 1st unnamed arg
	for(p = fmt; *p; p++)
	{
		if(*p != '%')
		{
			putchar(*p);
			continue;
		}

		int i;
		for(i = 0; i < 50 && !isalpha(*p); i++, p++)	// 将%以及其后的非字母字符存储存在数组中
			pfmt[i] = *p;
		pfmt[i++] = *p;
		pfmt[i] = '\0';
		// printf函数可以直接接受一个字符数组名，它会将数组名替换为“数组元素”形式，从而打印	

		switch(*p)
		{
		case 'i':
		case 'd':
		case 'c':
			ival = va_arg(ap, int);
			printf(pfmt, ival);
			break;
		case 'x':
		case 'X':
		case 'u':
		case 'o':
			uval = va_arg(ap, unsigned);
			printf(pfmt, uval);
			break;		
		case 'f':
		case 'e':
		case 'E':
		case 'g':
		case 'G':
			dval = va_arg(ap, double);
			printf(pfmt, dval);
			break;
		case 's':
		case 'p':
			sval = va_arg(ap, char *);
			printf(pfmt, sval);
			break;
		default:
			printf("%s", pfmt);
			break;
		}
	}
	va_end(ap);		// clean up when done
}

int main()
{
	minprintf("%3.3s\n", "sdadwadawdq");
	return 0;
}
